package coder.taiji.test.springnetty.udp;

import coder.taiji.test.springnetty.udp.dto.LogEvent;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Listing 13.7 LogEventHandler
 *
 * @author <a href="mailto:norman.maurer@gmail.com">Norman Maurer</a>
 */
public class LogEventHandler
		extends SimpleChannelInboundHandler<LogEvent> {

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx,
	                            Throwable cause) {

		System.out.println("udp 发生异常:" + cause);
		System.out.println("udp服务器抽象成这一个channle，所以千万不能关闭");
	}

	@Override
	public void channelRead0(ChannelHandlerContext ctx,
	                         LogEvent event) {
		LogEvent logEvent;
		if (!event.isSucc()) {
			System.out.println("错误的消息:" + event.toString());
			logEvent = new LogEvent(event.getSource(), System.currentTimeMillis(), "ddadsa", "recv error");
		} else {
			System.out.println("正确的消息:" + event.toString());
			logEvent = new LogEvent(event.getSource(), System.currentTimeMillis(), event.getLogfile(), "recv ok");
		}

		ctx.writeAndFlush(logEvent);
	}


}
